package com.br.unisal.library.database;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.br.unisal.library.database.utils.StatementConstants;
import com.br.unisal.library.exception.InvalidUserLoginData;
import com.br.unisal.library.operations.settings.LoginOperationSettings;


public class LoginDAO extends DatabaseOperationsImpl {

	private Integer user;
	private String password;
	
	public LoginDAO() {
		super();
	}
	
	@Override
	public boolean validateLogin(LoginOperationSettings loginSettings) throws InvalidUserLoginData {
		boolean retValue = false;
		extractSettings(loginSettings);
		if(isValidLogin()) {
			retValue = true;
		}
		return retValue;
	}

	private void extractSettings(LoginOperationSettings loginSettings) {
		this.user = loginSettings.getUser();
		this.password = loginSettings.getPassword();
	}

	private boolean isValidLogin() throws InvalidUserLoginData {
		boolean retValue = false;
		PreparedStatement ptmt = null;
		ResultSet resultSet = null;
		
		try {
			ptmt = connection.prepareStatement(StatementConstants.VALIDA_LOGIN);
			resultSet = ptmt.executeQuery();
			
			while (resultSet.next()) {
				int userID = resultSet.getInt(StatementConstants.USER_ID_COLUMN);
				String userPassword = resultSet.getString(StatementConstants.USER_PASSWORD);
				if((userID == user) & (userPassword.equals(password))){
					retValue = true;
					break;
				} else {
					throw new InvalidUserLoginData();
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return retValue;
	}
}
